package lex.dm.ui.results;

import java.awt.BorderLayout;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.*;

public class SingleResultSetPane extends JPanel {
	private JToolBar toolBar = null;
	private JButton previousButton = null;
	private JButton nextButton = null;
	private JSpinner maxRowsSpinner = null;
	private JTable table = null;
	private ResultSetTableModel tableModel = null;

	public SingleResultSetPane() {
		super();
		initialize();
	}

	public void setResultSet(final ResultSet rs) {
		try {
			getTableModel().setResultSet(rs);
			getTableModel().fireTableStructureChanged();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	private ResultSetTableModel getTableModel() {
		if (null == tableModel)
			tableModel = new ResultSetTableModel();
		return tableModel;
	}

	private JTable getTable() {
		if (table == null) {
			table = new JTable(this.getTableModel());
			table.setName(getClass().getName() + ".table");
			table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		}
		return table;
	}

	private void initialize() {
		this.setLayout(new BorderLayout());
		// this.add( getToolBar(), BorderLayout.NORTH );
		this.add(new JScrollPane(this.getTable()), BorderLayout.CENTER);
	}

	private JToolBar getToolBar() {
		if (toolBar == null) {
			toolBar = new JToolBar();
			toolBar.add(getPreviousButton());
			toolBar.add(getNextButton());
			toolBar.addSeparator();
			toolBar.add(new JLabel("Max Rows"));
			toolBar.add(getMaxRowsSpinner());
			toolBar.add(Box.createHorizontalGlue());
		}
		return toolBar;
	}

	private JButton getPreviousButton() {
		if (previousButton == null) {
			previousButton = new JButton();
			previousButton.setText("Previous");
		}
		return previousButton;
	}

	private JButton getNextButton() {
		if (nextButton == null) {
			nextButton = new JButton();
			nextButton.setText("Next");
		}
		return nextButton;
	}

	private JSpinner getMaxRowsSpinner() {
		if (maxRowsSpinner == null) {
			maxRowsSpinner = new JSpinner(new SpinnerNumberModel(100, 50, 500, 50));
		}
		return maxRowsSpinner;
	}
}
